from flask import Flask
from flask import render_template
from flask import request
from PIL import Image
import model
import time
import tensorflow as tf
import numpy as np



app = Flask(__name__)
basedir = 'D:/大学工作/网络开放源码体系/MyProject/zhenjiakankankan/flask/static/img/recognize/'

@app.route('/')
def index():
        return render_template("post_picture.html")

@app.route('/up_file',methods = ['POST'])
def up_file():
    img = request.files.get('photo')
    img.filename = str(time.time()) + img.filename
    img_filename = str(img.filename)
    file_path = basedir + img_filename
    img.save(file_path)
    result_id = {}#josn字典
    result_id['id'] = 0
    if file_path:
        result_id['id'] = 1
        ans = recognize(file_path)
        result_id['ans'] = ans

    return render_template('post_picture.html',**result_id)

def recognize(filename):
    image = proyourimage(filename)
    ans = evaluate_one_image(image)
    return ans

def proyourimage(filename):
    img = Image.open(filename)
    imag = img.resize([64,64])
    image = np.array(imag)
    return image

def evaluate_one_image(image_array):
    with tf.Graph().as_default():
        BATCH_SIZE = 1
        N_CLASSES = 4#这里设置为4个分类，测试的分类

        image = tf.cast(image_array, tf.float32)
        image = tf.image.per_image_standardization(image)
        image = tf.reshape(image, [1, 64, 64, 3])
        #调用模型
        logit = model.inference(image, BATCH_SIZE, N_CLASSES)
        logit = tf.nn.softmax(logit)
        x = tf.compat.v1.placeholder(tf.float32, shape=[64, 64, 3])#参数

        #设置路径
        logs_train_dir = 'train_log'
        saver = tf.compat.v1.train.Saver()
        #创建会话
        with tf.compat.v1.Session() as sess:

            print("Reading checkpoints...")
            ckpt = tf.train.get_checkpoint_state(logs_train_dir)
            if ckpt and ckpt.model_checkpoint_path:
                global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
                saver.restore(sess, ckpt.model_checkpoint_path)
                print('Loading success, global_step is %s' % global_step)
            else:
                print('No checkpoint file found')

            prediction = sess.run(logit, feed_dict={x: image_array})
            max_index = np.argmax(prediction)

            if max_index == 0:
                return 'Your AJ is a AJ1，为真'
            elif max_index == 1:
                return 'Your AJ is a AJ4，为真'
            elif max_index == 2:
                return 'Your AJ is a AJ11，为真'
            else: 
                return 'Your AJ is a aj12，为真'

if __name__ == '__main__':
    app.run(host = '0.0.0.0',debug = True)